import '../core.dart';
import '../model/log.dart';
import 'index.dart';

/// 限制error重复上报次数
NormalLogPipe createErrorLogLimitPipe(Core aegis) {
  Map<dynamic, int> logMap = {};

  return (List<NormalLog> logs, Resolve resolve) {
    int maxNum = aegis.config.repeat;
    if (maxNum == 0) {
      resolve(logs);

      return;
    }
    List<NormalLog> dedupLogs = logs.where((log) {
      if (log.level == LogType.error ||
          log.level == LogType.promiseError ||
          log.level == LogType.ajaxError ||
          log.level == LogType.scriptError ||
          log.level == LogType.imageError ||
          log.level == LogType.cssError ||
          log.level == LogType.mediaError) {
        logMap[log.msg] = logMap[log.msg] ?? 0;
        logMap[log.msg] = logMap[log.msg]! + 1;
        if (logMap[log.msg]! > maxNum) {
          return false;
        }

        return true;
      }

      return true;
    }).toList();
    resolve(dedupLogs);
  };
}
